#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "tcpsocketdialog.h"

#include <QNetworkInterface>
#include <QMessageBox>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    tcpServer(new QTcpServer(this))
{
    connect(tcpServer, SIGNAL(acceptError(QAbstractSocket::SocketError)), SLOT(on_acceptError(QAbstractSocket::SocketError)));
    connect(tcpServer, SIGNAL(newConnection()), SLOT(on_newConnection()));

    ui->setupUi(this);
    ui->btn_Stop->setVisible(false);
    ui->txt_IP->clear();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_acceptError(QAbstractSocket::SocketError socketError)
{
    qDebug() << socketError << tcpServer->errorString();
    ui->statusBar->showMessage(tcpServer->errorString());
}

void MainWindow::on_newConnection()
{
    ui->statusBar->showMessage(tr("接收到一个新连接。"));

    TcpSocketDialog dialog(tcpServer->nextPendingConnection());
    dialog.exec();
}

void MainWindow::on_btn_Start_clicked()
{
    if (!tcpServer->listen(QHostAddress::Any, ui->txt_Port->value())) {
        QMessageBox::critical(this, tr("TCP服务器"),
                              tr("无法启动服务： %1.")
                              .arg(tcpServer->errorString()));
        return;
    }

    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
                ipAddressesList.at(i).toIPv4Address()) {
            if(ipAddress.isEmpty()) {
                ipAddress.append(tr("%1").arg(ipAddressesList.at(i).toString()));
            } else {
                ipAddress.append(tr("\n%1").arg(ipAddressesList.at(i).toString()));
            }
        }
    }

    ui->txt_IP->setPlainText(ipAddress);
    ui->statusBar->showMessage(tr("启动服务成功！"));

    ui->txt_Port->setReadOnly(true);
    ui->btn_Start->setVisible(false);
    ui->btn_Stop->setVisible(true);
}

void MainWindow::on_btn_Stop_clicked()
{
    if(!tcpServer->isListening()) {
        QMessageBox::information(this, tr("TCP服务器"), tr("服务已经停止运行."));
        return;
    }

    tcpServer->close();
    ui->statusBar->showMessage(tr("服务已经停止！"));

    ui->txt_IP->clear();
    ui->txt_Port->setReadOnly(false);
    ui->btn_Start->setVisible(true);
    ui->btn_Stop->setVisible(false);
}
